// components/question/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    info: {
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showAnalysis: false,
    newInfo: {},
    answer: [],
    answerResult: false,
    score: 0
  },

  attached() {
    let newInfo = this.properties.info;
    let answer = this.data.info.ans.split(' ');
    let score = this.data.info.score;
    newInfo.items.forEach(i => {
      i.isSelect = false;
    });
    this.setData({
      newInfo,
      answer,
      score
    });
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleSelect(e) {
      let curIndex = e.currentTarget.dataset.index;
      let newInfo = this.data.info;
      let result = e.currentTarget.dataset.result;
      let curOption = e.currentTarget.dataset.option;
      newInfo.items[curIndex].isSelect = true;
      this.setData({
        newInfo,
        answerResult: result
      });
      if (result) {
        // 答对处理
        let arr = this.arrayRemoveItem(curOption);
        if (arr.length == 0) {
          this.showAnalysis();
        };
      } else {
        // 答错处理
        this.showAnalysis();
      }
    },

    showAnalysis() {
      setTimeout(() => {
        this.setData({
          showAnalysis: true
        })
      }, 500);
    },

    next() {
      let newInfo = this.data.newInfo;
      newInfo.items.forEach(i => {
        i.isSelect = false;
      });
      this.setData({
        showAnalysis: false,
        newInfo
      });
      let resultScore = this.data.answerResult ? this.data.score : 0;
      this.triggerEvent('next', resultScore);
    },

    // 数组去除元素
    arrayRemoveItem(del) {
      let arr = this.data.answer;
      if (arr instanceof Array) {
        let index = arr.indexOf(del);
        if (index > -1) {
          arr.splice(index, 1);
          this.setData({
            answer: arr
          })
          return arr;
        }
      }
    }
  }
})